/*
 * Copyright 2010 Yannick Stucki (yannickstucki.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yannickstucki.android.musicqueue.ui;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.yannickstucki.android.musicqueue.R;
import com.yannickstucki.android.musicqueue.data.Song;

/**
 * Generates view out of songs.
 * 
 * @author Yannick Stucki (yannickstucki@gmail.com)
 *
 */
public class SongViewGenerator implements IViewGenerator<Song> {

  /**
   * The context is needed for inflating.
   */
  private Context context;

  /**
   * The constructor takes a context to be able to inflate views.
   */
  public SongViewGenerator(Context context) {
    this.context = context;
  }

  @Override
  public View getView(View convertView, Song song) {
    if (convertView == null) {
      convertView = View.inflate(context, R.layout.row, null);
    }

    if (song == null) {
      return convertView;
    }
    TextView text = (TextView) convertView.findViewById(R.id.label);

    ImageView star;
    star = (ImageView) convertView.findViewById(R.id.star);

    text.setText(song.displayStrings[Song.currentDisplayStringIndex]);
    star.setVisibility(View.VISIBLE);

    if (song.starred) {
      star.setImageResource(R.drawable.starred);
    } else {
      star.setImageResource(R.drawable.unstarred);
    }

    star.setTag(song);
    star.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        Song song = (Song) v.getTag();
        song.starred = !song.starred;
        ImageView star2 = (ImageView) v;
        if (song.starred) {
          star2.setImageResource(R.drawable.starred);
          // songManager.addStarredSong(song);
        } else {
          star2.setImageResource(R.drawable.unstarred);
          // songManager.removeStarredSong(song);
        }
      }
    });

    return convertView;
  }
}
